package exer;

import java.util.Arrays;

public class HeapSort1 {
    public static void createHeap (int[] array) {
   //寻找最后一层的父节点
        int parent=(array.length-1-1)/2;
        for (int i = parent; i >=0 ; i--) {
            shiftDown(array,i, array.length);
        }

    }

    private static void shiftDown(int[] array, int parent, int length) {
        //定义孩子结点
        int child=(2*parent)+1;
        while(child< length){
            //先判断是否存在右孩子结点，并进行左右孩子结点大小的比较
            if(child+1<length){
                if(array[child+1]>array[child]){
                    child+=1;
                }
            }
            if(array[child]>array[parent]){
                //进行父子节点的交换
                swap(array,parent,child);
            }
            //将父子节点向下遍历
            parent=child;
            child=parent*2+1;
        }


    }

    private static void swap(int[] array, int parent, int child) {
        int temp=array[parent];
        array[parent]=array[child];
        array[child]=temp;
    }

    public static void sort(int[] array) {
        //先创建堆
        createHeap(array);
        //定义子节点
        int child= array.length-1;
        while(child>0){
            //将父子节点向下交换
            swap(array,0,child);
            //进行向下遍历
            shiftDown(array,0,child);
            child--;
        }



    }

    public static void main(String[] args) {
        int [] array = { 27,15,19,18,28,34,65,49,25,37 };
        sort(array);
        System.out.println(Arrays.toString(array));
    }
}